package com.gss.plugin.doc.config;

import com.github.xiaoymin.knife4j.spring.annotations.EnableKnife4j;
import com.gss.plugin.doc.properties.Knife4jProperties;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.OAuthBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.spring.web.plugins.WebFluxRequestHandlerProvider;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import javax.validation.constraints.NotNull;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: DYang
 * @since: 2023/8/17
 * @description: Knife4j swagger 配置
 */
@Configuration
@EnableSwagger2
@EnableKnife4j
@AllArgsConstructor
public class Knife4jSwaggerConfig {

    @Autowired
    private Knife4jProperties knife4jProperties;
    @Autowired
    private WebMvcProperties webMvcProperties;

    @Bean
    public Docket createRestApi() {
        // 设置 MatchingStrategy 为 ANT_PATH_MATCHER
        webMvcProperties.getPathmatch().setMatchingStrategy(WebMvcProperties.MatchingStrategy.ANT_PATH_MATCHER);

        Docket docket = new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .select()
                //加了ApiOperation注解的类，生成接口文档
                .apis(RequestHandlerSelectors.withMethodAnnotation(ApiOperation.class))
                //包下的类，生成接口文档
                .paths(PathSelectors.any())
                .build()
                .directModelSubstitute(Date.class, String.class);
        if (knife4jProperties.isSecurityMode()) {
            docket.securitySchemes(securityScheme());
        }
        return docket;
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(knife4jProperties.getProjectName())
                .description("work-order-desktop文档")
                .termsOfServiceUrl("http://www.dyang.com")
                .version("1.x")
                .build();
    }

    /**
     * 用于配置安全策略，比如配置认证模型，scope等内容
     */
    private List<SecurityScheme> securityScheme() {
        List<Knife4jProperties.SecurityBasic> securityBasicList = knife4jProperties.getSecurityBasics();
        if (securityBasicList == null || securityBasicList.isEmpty()) {
            return null;
        }
        List<SecurityScheme> securitySchemes = new ArrayList<>();
        for (Knife4jProperties.SecurityBasic basic : securityBasicList) {
            GrantType grantType = new ResourceOwnerPasswordCredentialsGrant(basic.getTokenUrl());
            AuthorizationScope scope = new AuthorizationScope(basic.getScope(), "");

            OAuth auth = new OAuthBuilder()
                    .name(basic.getName())
                    .grantTypes(Collections.singletonList(grantType))
                    .scopes(Collections.singletonList(scope))
                    .build();
            securitySchemes.add(auth);
        }
        return securitySchemes;
    }

    /**
     * 这里设置 swagger2 认证的安全上下文
     */
    private SecurityContext securityContext() {
        List<Knife4jProperties.SecurityBasic> securityBasicList = knife4jProperties.getSecurityBasics();
        if (securityBasicList == null || securityBasicList.isEmpty()) {
            return null;
        }
        List<SecurityReference> securityReferences = new ArrayList<>();

        for (Knife4jProperties.SecurityBasic securityBasic : securityBasicList) {
            AuthorizationScope[] scopes = new AuthorizationScope[1];
            scopes[0] = new AuthorizationScope(securityBasic.getScope(), "");
            securityReferences.add(new SecurityReference(securityBasic.getName(), scopes));
        }

        return SecurityContext.builder()
                .securityReferences(securityReferences)
                .forPaths(PathSelectors.any())
                .build();
    }

    /**
     * 解决springBoot2.7 与swagger不兼容问题
     */
    @Bean
    public static BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
        return new BeanPostProcessor() {
            @Override
            public Object postProcessAfterInitialization(@NotNull Object bean, @NotNull String beanName) throws BeansException {
                if (bean instanceof WebMvcRequestHandlerProvider || bean instanceof WebFluxRequestHandlerProvider) {
                    customizeSpringfoxHandlerMappings(getHandlerMappings(bean));
                }
                return bean;
            }

            private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
                List<T> copy = mappings.stream()
                        .filter(mapping -> mapping.getPatternParser() == null)
                        .collect(Collectors.toList());
                mappings.clear();
                mappings.addAll(copy);
            }

            @SuppressWarnings("unchecked")
            private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
                try {
                    Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");
                    assert field != null;
                    field.setAccessible(true);
                    return (List<RequestMappingInfoHandlerMapping>) field.get(bean);
                } catch (IllegalArgumentException | IllegalAccessException e) {
                    throw new IllegalStateException(e);
                }
            }
        };
    }
}
